package com.example.choupaiapp.main.activity.publish;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.XGridView;
import com.example.choupaiapp.common.view.XListView;
import com.example.choupaiapp.main.activity.TransparentActivity;
import com.example.choupaiapp.main.activity.home.CameraActivity;
import com.example.choupaiapp.main.bean.CameraDataBean;
import com.example.choupaiapp.main.bean.HomeTabBean;
import com.example.choupaiapp.main.bean.PreviewDataBean;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.TokenBean;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.fragment.HomeFragment;
import com.example.choupaiapp.main.util.DialogPublishDataCallback;
import com.example.choupaiapp.main.util.DialogPublishVoteCallback;
import com.example.choupaiapp.main.util.LocationUtil;
import com.example.choupaiapp.main.util.PublishDialog;
import com.example.choupaiapp.main.util.PublishVoteDialog;
import com.example.choupaiapp.main.view.DownloadProgressButton;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.shuyu.textutillib.RichTextView;
import com.shuyu.textutillib.model.UserModel;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2020/4/22.
 */

public class PublishNewActivity extends CommonActivity implements DialogPublishDataCallback, DialogPublishVoteCallback, AMapLocationListener {

    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.gridview)
    XGridView gridview;
    @BindView(R.id.edit)
    RichTextView edit;
    @BindView(R.id.publish_tv)
    TextView publishTv;
    @BindView(R.id.complete_img)
    ImageView completeImg;
    @BindView(R.id.btn_progress)
    DownloadProgressButton btn_progress;
    @BindView(R.id.tab_gridview)
    TagFlowLayout tab_gridview;
    @BindView(R.id.publish)
    RelativeLayout publish;
    @BindView(R.id.vote_rl)
    RelativeLayout vote_rl;
    @BindView(R.id.vote_listview)
    XListView vote_listview;
    @BindView(R.id.tab_ll)
    LinearLayout tab_ll;
    private AMap aMap;
    private UiSettings mUiSettings;
    private LatLng latLng;
    private int anonymous = 0;
    private int pageNum = 0;
    private int num = 10;
    private boolean isPublish = true;
    @BindView(R.id.location_tv)
    TextView location_tv;
    @BindView(R.id.location_iv)
    ImageView location_iv;

    private Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (btn_progress.getProgress() >= 90) {

            } else {
                runOnUiThread(() -> {
                    btn_progress.setProgress(num += 10);
                    btn_progress.postInvalidate();
                    handler.postDelayed(runnable, 1000);
                });
            }

        }
    };
    private QuickAdapter<String> quickAdapter;
    private ArrayList<String> list;
    private String flag;
    private String isVideo;
    private Random random;
    private List<String> urlList;
    private String address;
    private String addressPoi;
    private double lot;
    private double lat;
    private String adCode;
    private String province;
    private String city;
    private String district;
    private String street;
    //    private QuickAdapter<HomeTabBean.ListBean> tabAdapter;
    private int index = -1;
    private String isEmpty;
    private PublishDialog publishDialog;
    private boolean isLocation = false;
    private List<UserModel> nameList;
    private int vote = 0;
    private List<String> stringList = new ArrayList<>();
    private HashMap<Integer, String> stringMap;
    private boolean isReturnLocation = false;
    private String shootTime = "";
    private String citycode;
    private List<HomeTabBean.ListBean> tabList;
    private TagAdapter<HomeTabBean.ListBean> tagAdapter;

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void tokenVerify() {
        HttpParams params = new HttpParams();
        params.put("token", (String) SharedPreferencesHelp.get("token", ""));
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.VERIFY_TOKEN, params, Url.VERIFY_TOKEN, new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                    publishDialog = new PublishDialog();
                    publishDialog.show(getFragmentManager(), "PublishDialog");
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_new);
        mapView.onCreate(savedInstanceState); // 此方法必须重写

        latLng = new LatLng(HomeFragment.lat, HomeFragment.lon);

        if (aMap == null) {
            aMap = mapView.getMap();
            mUiSettings = aMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(false);
            mUiSettings.setTiltGesturesEnabled(false);
            mUiSettings.setZoomGesturesEnabled(false);
            mUiSettings.setScrollGesturesEnabled(false);
            mUiSettings.setRotateGesturesEnabled(false);
            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 18, 30, 30)));
        }
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                addMarkersToMap();
            }
        });
    }

    private void addMarkersToMap() {
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        Marker marker = aMap.addMarker(new MarkerOptions()
                .position(latLng)
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromView(getLayoutInflater().inflate(R.layout.publish_map_marker_small, null)))
                .draggable(true));
        marker.setPositionByPixels(screenPosition.x, screenPosition.y);

//        geocoder();
    }

    @Override
    protected void initView() {
        setTitle("发布新内容");

        random = new Random();

        EventBus.getDefault().register(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            flag = bundle.getString("flag");
            isVideo = bundle.getString("isVideo");
            list = bundle.getStringArrayList("path");
            shootTime = bundle.getString("shootTime");
        }

        if (flag.equals("text")) {
            gridview.setVisibility(View.GONE);
        } else {
            gridview.setVisibility(View.VISIBLE);

            quickAdapter = new QuickAdapter<String>(context, R.layout.item_add_photo) {
                @Override
                protected void convert(BaseAdapterHelper helper, String item) {
                    ImageView photo = helper.getView(R.id.photo);
                    ImageView delete_img = helper.getView(R.id.delete_img);

                    if (item.equals("empty")) {
                        delete_img.setVisibility(View.INVISIBLE);
                        Glide.with(context).load(R.mipmap.icon_add_photo).crossFade().into(photo);
                        photo.setOnClickListener(view -> {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            if (rxPermissions.isGranted(Manifest.permission.CAMERA)) {
                                if (rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    showTakePhoto();
                                } else {
                                    rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(aBoolean -> {
                                        if (aBoolean) {
                                            showTakePhoto();
                                        } else {
                                            showToast("拒绝权限可能导致功能不能正常使用");
                                        }
                                    });
                                }
                            } else {
                                rxPermissions.request(Manifest.permission.CAMERA).subscribe(aBoolean -> {
                                    if (aBoolean) {
                                        if (rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                            showTakePhoto();
                                        } else {
                                            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(aBoolean1 -> {
                                                if (aBoolean1) {
                                                    showTakePhoto();
                                                } else {
                                                    showToast("拒绝权限可能导致功能不能正常使用");
                                                }
                                            });
                                        }
                                    } else {
                                        showToast("拒绝权限可能导致功能不能正常使用");
                                    }
                                });
                            }
                        });
                    } else {
                        delete_img.setVisibility(View.VISIBLE);
                        Glide.with(context)
                                .load(item.contains("content://") ? Uri.parse(item) : item)
                                .skipMemoryCache(true)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .centerCrop()
                                .crossFade()
                                .into(photo);
                        photo.setOnClickListener(view -> {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            if ("yes".equals(isVideo)) {
                                Bundle bundle1 = new Bundle();
                                bundle1.putString("path", quickAdapter.getItem(helper.getPosition()));
                                startActivity(PublishVideoPreviewActivity.class, bundle1);
                            } else {
                                if (quickAdapter.getCount() == 9) {
                                    if (quickAdapter.getItem(quickAdapter.getCount() - 1).equals("empty")) {
                                        ArrayList<String> list = new ArrayList<>();
                                        for (int j = 0; j < quickAdapter.getCount() - 1; j++) {
                                            list.add(quickAdapter.getItem(j));
                                        }
                                        Bundle bundle1 = new Bundle();
                                        bundle1.putStringArrayList("path", list);
                                        bundle1.putInt("position", helper.getPosition());
                                        startActivity(PublishPicturePreviewActivity.class, bundle1);
                                    } else {
                                        ArrayList<String> list = new ArrayList<>();
                                        for (int j = 0; j < quickAdapter.getCount(); j++) {
                                            list.add(quickAdapter.getItem(j));
                                        }
                                        Bundle bundle1 = new Bundle();
                                        bundle1.putStringArrayList("path", list);
                                        bundle1.putInt("position", helper.getPosition());
                                        startActivity(PublishPicturePreviewActivity.class, bundle1);
                                    }

                                } else {
                                    ArrayList<String> list = new ArrayList<>();
                                    for (int j = 0; j < quickAdapter.getCount() - 1; j++) {
                                        list.add(quickAdapter.getItem(j));
                                    }
                                    Bundle bundle1 = new Bundle();
                                    bundle1.putStringArrayList("path", list);
                                    bundle1.putInt("position", helper.getPosition());
                                    startActivity(PublishPicturePreviewActivity.class, bundle1);
                                }
                            }
                        });
                    }

                    delete_img.setOnClickListener(view -> {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        quickAdapter.remove(item);
                        if ("yes".equals(isVideo)) {
                            quickAdapter.add("empty");
                            isEmpty = "yes";
                        } else {
                            if (quickAdapter.getCount() == 1) {
                                isEmpty = "yes";
                            } else {
                                if (quickAdapter.getCount() == 8 && !quickAdapter.getItem(quickAdapter.getCount() - 1).equals("empty")) {
                                    quickAdapter.add("empty");
                                }
                                isEmpty = "no";
                            }
                        }
                        quickAdapter.notifyDataSetChanged();
                    });
                }
            };

            gridview.setAdapter(quickAdapter);

            quickAdapter.clear();
            quickAdapter.addAll(list);
            isEmpty = "no";
            if ("yes".equals(isVideo)) {
            } else {
                if (list.size() >= 9) {
                } else {
                    quickAdapter.add("empty");
                }
            }
            quickAdapter.notifyDataSetChanged();

        }


        tabList = new ArrayList<>();
        tagAdapter = new TagAdapter<HomeTabBean.ListBean>(tabList) {
            @Override
            public View getView(FlowLayout parent, int position, HomeTabBean.ListBean listBean) {
                View view = View.inflate(context, R.layout.item_publish_tab, null);
                TextView textView = view.findViewById(R.id.location_tv);
                textView.setText(listBean.getName());
                if (listBean.isSelected()) {
                    textView.setBackgroundResource(R.drawable.shape_publish_map_sure_btn);
                } else {
                    textView.setBackgroundResource(R.drawable.shape_gray_oval);
                }
                return view;
            }

        };
        tab_gridview.setAdapter(tagAdapter);

        tab_gridview.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                for (int j = 0; j < tagAdapter.getCount(); j++) {
                    tagAdapter.getItem(j).setSelected(false);
                }
                tagAdapter.getItem(position).setSelected(true);
                index = position;
                tagAdapter.notifyDataChanged();
                return true;
            }
        });


        btn_progress.setState(DownloadProgressButton.STATE_DOWNLOADING);
        btn_progress.setMaxProgress(100);
        btn_progress.setShowBorder(false);

        nameList = new ArrayList<>();
        //直接使用RichTextView
        edit.setAtColor(Color.parseColor(getString(R.string.remind_color)));
        edit.setLinkColor(Color.BLUE);
        //所有配置完成后才设置text
        edit.setNameList(nameList);

    }

    @Override
    protected void initData() {

        if (rxPermissions.isGranted(Manifest.permission.ACCESS_COARSE_LOCATION) && rxPermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)
                && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE) && rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
            /*&& rxPermissions.isGranted(Manifest.permission.READ_PHONE_STATE)*/) {

            LocationUtil.getInstance().locationOption();
            LocationUtil.getInstance().setLocationListener(this);
            LocationUtil.getInstance().startLocation();
        } else {
            rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE/*, Manifest.permission.READ_PHONE_STATE*/).subscribe(aBoolean -> {
                if (aBoolean) {
                    LocationUtil.getInstance().locationOption();
                    LocationUtil.getInstance().setLocationListener(PublishNewActivity.this);
                    LocationUtil.getInstance().startLocation();
                } else {
                    showImageToas("您似乎关闭了位置服务，请在设置中打开");
                }
            });
        }

        showDialog(context, null);
        HttpParams params = new HttpParams();
        params.put("fixed", 0);
        finalOkGo.request(RequestType.POST, Url.HOME_TAB, params, Url.HOME_TAB, new Callback<HomeTabBean>() {
            @Override
            public void onSuccess(HomeTabBean homeTabBean) {
                dismissDialog();
                if (homeTabBean.getCode() == Contacts.SUCCESS) {
                    tabList.clear();
                    tabList.addAll(homeTabBean.getList());
                    tagAdapter.notifyDataChanged();
                } else {
                    showImageToas("获取标签失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    private void showTakePhoto() {
        Bundle bundle = new Bundle();
        bundle.putString("flag", "in");
        bundle.putString("isEmpty", isEmpty);
        bundle.putInt("count", 9 - quickAdapter.getCount() + 1);
        startActivity(CameraActivity.class, bundle);

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.location_rl, R.id.location_view, R.id.vote_delete, R.id.edit, R.id.ll_desc, R.id.publish})
    public void onViewClicked(View view) {
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_desc:
                DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_publish_desc);
                LinearLayout dialog_publish_desc = (LinearLayout) DialogUtil.getInstance().dialog_center_layout;
                dialog_publish_desc.findViewById(R.id.mine_know).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DialogUtil.getInstance().dialog_center.dismiss();
                    }
                });
                break;
            case R.id.edit:
                tokenVerify();
                break;
            case R.id.location_rl:
                if (!TextUtils.isEmpty(citycode)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("citycode", citycode);
                    bundle.putString("city", city);
                    bundle.putDouble("lat", latLng.latitude);
                    bundle.putDouble("lon", latLng.longitude);
                    startActivity(PublishMapViewActivity.class, bundle);
                } else {
                    showImageToas("请稍等，正在获取定位数据");
                }
                break;
            case R.id.location_view:
                if (!TextUtils.isEmpty(citycode)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("citycode", citycode);
                    bundle.putString("city", city);
                    bundle.putDouble("lat", latLng.latitude);
                    bundle.putDouble("lon", latLng.longitude);
                    startActivity(PublishMapViewActivity.class, bundle);
                } else {
                    showImageToas("请稍等，正在获取定位数据");
                }
                break;
            case R.id.vote_delete:
                vote = 0;
                stringList.clear();
                stringMap.clear();
                vote_rl.setVisibility(View.GONE);
                break;
            case R.id.publish:
                if (isPublish) {
                    isPublish = false;
                    urlList = new ArrayList<>();
                    if (isReturnLocation) {
                        if ("text".equals(flag)) {
                            if (!TextUtils.isEmpty(edit.getText().toString().trim()) && edit.getText().toString().length() >= 5) {
                                //发布
                                if (index == -1) {
                                    isPublish = true;
                                    showImageToas("请选择分类");
                                } else {
                                    publish_text();
                                }
                            } else {
                                isPublish = true;
                                showImageToas("至少输入5个字哦");
                            }
                        } else {
                            if ("no".equals(isEmpty)) {
                                if (index == -1) {
                                    isPublish = true;
                                    showImageToas("请选择分类");
                                } else {
                                    if (publishTv.getText().toString().equals("发布")) {
                                        publishTv.setText("发布中");
                                        btn_progress.setState(DownloadProgressButton.STATE_DOWNLOADING);
                                        handler.postDelayed(runnable, 1000);
                                    } else if (publishTv.getText().toString().equals("重试")) {
                                        num = 10;
                                        btn_progress.setProgress(0);
                                        publishTv.setText("发布中");
                                        btn_progress.setState(DownloadProgressButton.STATE_DOWNLOADING);
                                        handler.postDelayed(runnable, 1000);
                                    }
                                    upLoadPic(quickAdapter.getItem(pageNum));
                                }

                            } else {
                                if (!TextUtils.isEmpty(edit.getText().toString().trim()) && edit.getText().toString().length() >= 5) {
                                    //发布
                                    if (index == -1) {
                                        isPublish = true;
                                        showImageToas("请选择分类");
                                    } else {
                                        publish_text();
                                    }
                                } else {
                                    isPublish = true;
                                    showImageToas("至少输入5个字哦");
                                }
                            }
                        }
                    } else {
                        isPublish = true;
                        showImageToas("请选择事件位置");
                    }
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        String s = event.split(":")[0];
        if (s.equals("location_mapView")) {
            Logger.e(event);
            String lat = event.split(":")[1];
            String lon = event.split(":")[2];
            latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lon));
            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 18, 30, 30)));

            geocoder();
        }
    }


    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(CameraDataBean event) {
        quickAdapter.remove("empty");
        quickAdapter.addAll(event.getList());
        isVideo = event.getIsVideo();
        isEmpty = "no";
        shootTime = event.getTime();
        Logger.e(shootTime);
        if ("yes".equals(isVideo)) {
        } else {
            if (quickAdapter.getCount() >= 9) {
            } else {
                quickAdapter.add("empty");
            }
        }
        quickAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(PreviewDataBean event) {
        quickAdapter.clear();
        quickAdapter.addAll(event.getList());
        isVideo = event.getIsVideo();
        if (event.getList().size() > 0) {
            isEmpty = "no";
        } else {
            isEmpty = "yes";
        }
        if ("yes".equals(isVideo)) {
            quickAdapter.add("empty");
        } else {
            if (quickAdapter.getCount() >= 9) {
            } else {
                quickAdapter.add("empty");
            }
        }
        quickAdapter.notifyDataSetChanged();
    }

    private void geocoder() {
//        LatLonPoint point = new LatLonPoint(latLng.latitude, latLng.longitude);
//        GeocodeSearch geocoderSearch = new GeocodeSearch(context);
//        RegeocodeQuery query = new RegeocodeQuery(point, 200F, GeocodeSearch.AMAP);
//
//        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
//            @Override
//            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
//                isReturnLocation = true;
////                Logger.e(regeocodeResult.getRegeocodeAddress().getRoads().size() + "");
////
////                Logger.e("逆定位数据" + regeocodeResult.getRegeocodeAddress().getAdCode()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getBuilding()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getCity()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getCityCode()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getCountry()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getDistrict()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getFormatAddress()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getNeighborhood()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getProvince()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getTownship()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getRoads().get(0).getName()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getAois().get(0).getAoiName()
////                        + "+++" + regeocodeResult.getRegeocodeAddress().getPois().get(0).getTitle());
//
//                address = regeocodeResult.getRegeocodeAddress().getFormatAddress();
//                addressPoi = regeocodeResult.getRegeocodeAddress().getAois().size() == 0 ? (regeocodeResult.getRegeocodeAddress().getPois().size() == 0 ? "" : regeocodeResult.getRegeocodeAddress().getPois().get(0).getTitle()) : regeocodeResult.getRegeocodeAddress().getAois().get(0).getAoiName();
//                lot = latLng.longitude;
//                lat = latLng.latitude;
//                adCode = regeocodeResult.getRegeocodeAddress().getAdCode();
//                province = regeocodeResult.getRegeocodeAddress().getProvince();
//                city = regeocodeResult.getRegeocodeAddress().getCity();
//                district = regeocodeResult.getRegeocodeAddress().getDistrict();
//                street = regeocodeResult.getRegeocodeAddress().getTownship();
//
//                location_tv.setText(addressPoi);
//
//            }
//
//            @Override
//            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
//            }
//
//        });
//        geocoderSearch.getFromLocationAsyn(query);

        LocationUtil.getInstance().searchPoiOption(city, citycode, new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                if (poiResult.getPois() != null && poiResult.getPois().size() != 0) {
                    address = poiResult.getPois().get(0).getProvinceName() + poiResult.getPois().get(0).getCityName() + poiResult.getPois().get(0).getAdName() + poiResult.getPois().get(0).getSnippet();
                    addressPoi = poiResult.getPois().get(0).getTitle();
                    lot = latLng.longitude;
                    lat = latLng.latitude;
                    adCode = poiResult.getPois().get(0).getAdCode();
                    province = poiResult.getPois().get(0).getProvinceName();
                    city = poiResult.getPois().get(0).getCityName();
                    district = poiResult.getPois().get(0).getAdName();
                    if (!TextUtils.isEmpty(poiResult.getPois().get(0).getSnippet())) {
                        street = poiResult.getPois().get(0).getSnippet();
                    } else {
                        if (!TextUtils.isEmpty(poiResult.getPois().get(0).getBusinessArea())) {
                            street = poiResult.getPois().get(0).getBusinessArea();
                        } else {
                            street = poiResult.getPois().get(0).getDirection();
                        }
                    }
                    location_iv.setVisibility(View.VISIBLE);
                    location_tv.setText(city + "-" + addressPoi);
                    isReturnLocation = true;
                }

            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        }, 10000, latLng.latitude, latLng.longitude);
        LocationUtil.getInstance().setQuery(1, 1);
        LocationUtil.getInstance().searchPoi();
    }

    @Override
    public String getCommentText() {
        return edit.getText().toString();
    }

    @Override
    public List<UserModel> getNameList() {
        for (int i = 0; i < edit.getNameList().size(); i++) {
            edit.getNameList().get(i).setUser_name("@" + edit.getNameList().get(i).getUser_name());
        }
        Logger.e("getNameList" + edit.getNameList().toString());
        return edit.getNameList();
    }

    @Override
    public void setNameList(List<UserModel> nameList) {
        Logger.e("setNameList" + nameList.toString());
        edit.setNameList(nameList);
    }

    @Override
    public void setCommentText(String commentTextTemp) {
        if (!TextUtils.isEmpty(commentTextTemp)) {
            edit.setRichText(commentTextTemp);
        } else {
            edit.setText(commentTextTemp);
        }
    }

    @Override
    public int isAnonymous() {
        return anonymous;
    }

    @Override
    public void setAnonymous(int anonymous) {
        this.anonymous = anonymous;
    }

    @Override
    public int isVote() {
        return vote;
    }

    @Override
    public void setVote(int vote) {
        this.vote = vote;
        PublishVoteDialog publishVoteDialog = new PublishVoteDialog();
        publishVoteDialog.show(getFragmentManager(), "PublishVoteDialog");
    }

    @Override
    public void setVoteList(HashMap<Integer, String> map) {
        stringMap = map;
        stringList.clear();
        for (int i = 0; i < map.size(); i++) {
            stringList.add(map.get(i));
        }
        vote_rl.setVisibility(View.VISIBLE);
        QuickAdapter<String> quickAdapter = new QuickAdapter<String>(this, R.layout.item_vote_publish, stringList) {
            @Override
            protected void convert(BaseAdapterHelper helper, String item) {
                helper.setText(R.id.textview, item);
            }
        };
        vote_listview.setAdapter(quickAdapter);

        vote_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                PublishVoteDialog publishVoteDialog = new PublishVoteDialog();
                publishVoteDialog.show(getFragmentManager(), "PublishVoteDialog");
            }
        });
    }

    @Override
    public HashMap<Integer, String> getVoteList() {
        return stringMap == null ? new HashMap<>() : stringMap;
    }


    private void publish_text() {
        publish.setEnabled(false);
        if (publishTv.getText().toString().equals("发布")) {
            publishTv.setText("发布中");
            btn_progress.setState(DownloadProgressButton.STATE_DOWNLOADING);
            handler.postDelayed(runnable, 1000);
        } else if (publishTv.getText().toString().equals("重试")) {
            num = 10;
            btn_progress.setProgress(0);
            publishTv.setText("发布中");
            btn_progress.setState(DownloadProgressButton.STATE_DOWNLOADING);
            handler.postDelayed(runnable, 1000);
        }
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        JSONArray jsonArrayVote = new JSONArray();
        try {
            for (int i = 0; i < edit.getNameList().size(); i++) {
                JSONObject userJson = new JSONObject();
                userJson.put("nickname", edit.getNameList().get(i).getUser_name());
                userJson.put("userId", edit.getNameList().get(i).getUser_id());
                jsonArray.put(userJson);
            }
            for (int i = 0; i < stringList.size(); i++) {
                JSONObject voteJson = new JSONObject();
                voteJson.put("name", stringList.get(i));
                jsonArrayVote.put(voteJson);
            }
            jsonObject.put("contentVoteJson", jsonArrayVote.toString());
            jsonObject.put("remindJson", jsonArray.toString());
            jsonObject.put("title", edit.getText().toString().trim());
            jsonObject.put("anonymity", anonymous);
            jsonObject.put("categoriesId", tagAdapter.getItem(index).getId());
            jsonObject.put("type", 3);
            jsonObject.put("address", addressPoi + "|" + address);
            jsonObject.put("longitude", lot);
            jsonObject.put("latitude", lat);
            jsonObject.put("adCode", adCode);
            jsonObject.put("province", province);
            jsonObject.put("city", city);
            jsonObject.put("district", district);
            jsonObject.put("street", street);
            jsonObject.put("shootTime", shootTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.e(jsonObject.toString());
        finalOkGo.requestHead(RequestType.POSTJSONHEADNOCACHE, Url.PUBLISH, null, jsonObject.toString(), new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                dismissDialog();
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                    btn_progress.setState(DownloadProgressButton.STATE_NORMAL);
                    publishTv.setText("");
                    completeImg.setVisibility(View.VISIBLE);
                    handler.removeCallbacks(runnable);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isPublish = true;
                            publish.setEnabled(true);
                            Bundle bundle = new Bundle();
                            bundle.putString("flag", "publish");
                            startFinishActivity(TransparentActivity.class, bundle);
//                            finishActivity();
                        }
                    }, 1000);
                } else {
                    isPublish = true;
                    publish.setEnabled(true);
                    btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                    publishTv.setText("重试");
                    handler.removeCallbacks(runnable);
                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(sendCodeBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
                isPublish = true;
                publish.setEnabled(true);
                btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                publishTv.setText("重试");
                handler.removeCallbacks(runnable);
            }
        });
    }


    private void upLoadPic(String path) {
        publish.setEnabled(false);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.GET_QINIU_TOKEN, null, Url.GET_QINIU_TOKEN, new Callback<TokenBean>() {
            @Override
            public void onSuccess(TokenBean tokenBean) {
                if (tokenBean.getCode() == Contacts.SUCCESS) {
                    Configuration config = new Configuration.Builder()
                            .build();
                    // 重用uploadManager。一般地，只需要创建一个uploadManager对象
                    UploadManager uploadManager = new UploadManager(config);//配置3个线程数并发上传；不配置默认为3，只针对file.size>4M生效。线程数建议不超过5，上传速度主要取决于上行带宽，带宽很小的情况单线程和多线程没有区别

                    String keyName = System.currentTimeMillis() + "" + (random.nextInt(999999) + 1) + path.substring(path.lastIndexOf("."));

                    uploadManager.put(path, keyName, tokenBean.getToken(), new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {

//                                Logger.e(Url.QINIU_YUN + key);
                                urlList.add(Url.QINIU_YUN + key);

                                pageNum = pageNum + 1;
//                                if (quickAdapter.getCount() == 9) {
                                if ("empty".equals(quickAdapter.getItem(quickAdapter.getCount() - 1))) {
                                    if (pageNum < quickAdapter.getCount() - 1) {
                                        upLoadPic(quickAdapter.getItem(pageNum));
                                    } else {
                                        pageNum = 0;
                                        //传服务器
                                        String string = "";
                                        for (int i = 0; i < urlList.size(); i++) {
                                            if (i == urlList.size() - 1) {
                                                string = string + urlList.get(i);
                                            } else {
                                                string = string + urlList.get(i) + "|";
                                            }
                                        }

                                        if (isVideo.equals("yes")) {
                                            String finalString = string;
                                            Glide.with(context)
                                                    .load(path.contains("content://") ? Uri.parse(path) : path)
                                                    .asBitmap()
                                                    .into(new SimpleTarget<Bitmap>() {
                                                        @Override
                                                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                                            JSONObject jsonObject = new JSONObject();
                                                            JSONArray jsonArray = new JSONArray();
                                                            JSONArray jsonArrayVote = new JSONArray();
                                                            try {
                                                                for (int i = 0; i < edit.getNameList().size(); i++) {
                                                                    JSONObject userJson = new JSONObject();
                                                                    userJson.put("nickname", edit.getNameList().get(i).getUser_name());
                                                                    userJson.put("userId", edit.getNameList().get(i).getUser_id());
                                                                    jsonArray.put(userJson);
                                                                }
                                                                for (int i = 0; i < stringList.size(); i++) {
                                                                    JSONObject voteJson = new JSONObject();
                                                                    voteJson.put("name", stringList.get(i));
                                                                    jsonArrayVote.put(voteJson);
                                                                }
                                                                jsonObject.put("contentVoteJson", jsonArrayVote.toString());
                                                                jsonObject.put("remindJson", jsonArray.toString());
                                                                jsonObject.put("title", edit.getText().toString().trim());
                                                                jsonObject.put("anonymity", anonymous);
                                                                if (urlList.size() > 0) {
                                                                    if (isVideo.equals("yes")) {
                                                                        jsonObject.put("type", 1);
                                                                        jsonObject.put("videoWidth", resource.getWidth());
                                                                        jsonObject.put("videoHeight", resource.getHeight());
                                                                        jsonObject.put("videoDuration", Integer.parseInt(getDuration(finalString)) / 1000);
                                                                    } else {
                                                                        jsonObject.put("type", 2);
                                                                    }
                                                                } else {
                                                                    jsonObject.put("type", 3);
                                                                }
                                                                jsonObject.put("urls", finalString);
                                                                jsonObject.put("address", addressPoi + "|" + address);
                                                                jsonObject.put("categoriesId", tagAdapter.getItem(index).getId());
                                                                jsonObject.put("longitude", lot);
                                                                jsonObject.put("latitude", lat);
                                                                jsonObject.put("adCode", adCode);
                                                                jsonObject.put("province", province);
                                                                jsonObject.put("city", city);
                                                                jsonObject.put("district", district);
                                                                jsonObject.put("street", street);
                                                                jsonObject.put("shootTime", shootTime);
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }

                                                            Logger.e(jsonObject.toString());
                                                            finalOkGo.requestHead(RequestType.POSTJSONHEADNOCACHE, Url.PUBLISH, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                                                @Override
                                                                public void onSuccess(SendCodeBean sendCodeBean) {
                                                                    dismissDialog();
                                                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                                        btn_progress.setState(DownloadProgressButton.STATE_NORMAL);
                                                                        publishTv.setText("");
                                                                        completeImg.setVisibility(View.VISIBLE);
                                                                        handler.removeCallbacks(runnable);
                                                                        new Handler().postDelayed(new Runnable() {
                                                                            @Override
                                                                            public void run() {
                                                                                isPublish = true;
                                                                                publish.setEnabled(true);
                                                                                Bundle bundle = new Bundle();
                                                                                bundle.putString("flag", "publish");
                                                                                startFinishActivity(TransparentActivity.class, bundle);
                                                                            }
                                                                        }, 1000);
                                                                    } else {
                                                                        showImageToas(sendCodeBean.getMsg());
                                                                        isPublish = true;
                                                                        publish.setEnabled(true);
                                                                        btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                                                                        publishTv.setText("重试");
                                                                        handler.removeCallbacks(runnable);
                                                                    }
                                                                }

                                                                @Override
                                                                public void onError(Response<String> response) {
                                                                    super.onError(response);
                                                                    dismissDialog();
                                                                    isPublish = true;
                                                                    publish.setEnabled(true);
                                                                    btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                                                                    publishTv.setText("重试");
                                                                    handler.removeCallbacks(runnable);
                                                                }
                                                            });
                                                        }

                                                    });

                                        } else {
                                            JSONObject jsonObject = new JSONObject();
                                            JSONArray jsonArray = new JSONArray();
                                            JSONArray jsonArrayVote = new JSONArray();
                                            try {
                                                for (int i = 0; i < edit.getNameList().size(); i++) {
                                                    JSONObject userJson = new JSONObject();
                                                    userJson.put("nickname", edit.getNameList().get(i).getUser_name());
                                                    userJson.put("userId", edit.getNameList().get(i).getUser_id());
                                                    jsonArray.put(userJson);
                                                }
                                                for (int i = 0; i < stringList.size(); i++) {
                                                    JSONObject voteJson = new JSONObject();
                                                    voteJson.put("name", stringList.get(i));
                                                    jsonArrayVote.put(voteJson);
                                                }
                                                jsonObject.put("contentVoteJson", jsonArrayVote.toString());
                                                jsonObject.put("remindJson", jsonArray.toString());
                                                jsonObject.put("title", edit.getText().toString().trim());
                                                jsonObject.put("anonymity", anonymous);
                                                if (urlList.size() > 0) {
                                                    if (isVideo.equals("yes")) {
                                                        jsonObject.put("type", 1);
                                                    } else {
                                                        jsonObject.put("type", 2);
                                                    }
                                                } else {
                                                    jsonObject.put("type", 3);
                                                }
                                                jsonObject.put("urls", string);
                                                jsonObject.put("address", addressPoi + "|" + address);
                                                jsonObject.put("categoriesId", tagAdapter.getItem(index).getId());
                                                jsonObject.put("longitude", lot);
                                                jsonObject.put("latitude", lat);
                                                jsonObject.put("adCode", adCode);
                                                jsonObject.put("province", province);
                                                jsonObject.put("city", city);
                                                jsonObject.put("district", district);
                                                jsonObject.put("street", street);
                                                jsonObject.put("shootTime", shootTime);
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }

                                            Logger.e(jsonObject.toString());
                                            finalOkGo.requestHead(RequestType.POSTJSONHEADNOCACHE, Url.PUBLISH, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                                @Override
                                                public void onSuccess(SendCodeBean sendCodeBean) {
                                                    dismissDialog();
                                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                        btn_progress.setState(DownloadProgressButton.STATE_NORMAL);
                                                        publishTv.setText("");
                                                        completeImg.setVisibility(View.VISIBLE);
                                                        handler.removeCallbacks(runnable);
                                                        new Handler().postDelayed(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                isPublish = true;
                                                                publish.setEnabled(true);
                                                                Bundle bundle = new Bundle();
                                                                bundle.putString("flag", "publish");
                                                                startFinishActivity(TransparentActivity.class, bundle);
                                                            }
                                                        }, 1000);
                                                    } else {
                                                        showImageToas(sendCodeBean.getMsg());
                                                        isPublish = true;
                                                        publish.setEnabled(true);
                                                        btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                                                        publishTv.setText("重试");
                                                        handler.removeCallbacks(runnable);
                                                    }
                                                }

                                                @Override
                                                public void onError(Response<String> response) {
                                                    super.onError(response);
                                                    dismissDialog();
                                                    isPublish = true;
                                                    publish.setEnabled(true);
                                                    btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                                                    publishTv.setText("重试");
                                                    handler.removeCallbacks(runnable);
                                                }
                                            });
                                        }
                                    }
                                } else {
                                    if (pageNum < quickAdapter.getCount()) {
                                        upLoadPic(quickAdapter.getItem(pageNum));
                                    } else {
                                        pageNum = 0;
                                        //传服务器
                                        String string = "";
                                        for (int i = 0; i < urlList.size(); i++) {
                                            if (i == urlList.size() - 1) {
                                                string = string + urlList.get(i);
                                            } else {
                                                string = string + urlList.get(i) + "|";
                                            }
                                        }

                                        if (isVideo.equals("yes")) {
                                            String finalString = string;
                                            Glide.with(context)
                                                    .load(path.contains("content://") ? Uri.parse(path) : path)
                                                    .asBitmap()
                                                    .into(new SimpleTarget<Bitmap>() {
                                                        @Override
                                                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                                            JSONObject jsonObject = new JSONObject();
                                                            JSONArray jsonArray = new JSONArray();
                                                            JSONArray jsonArrayVote = new JSONArray();
                                                            try {
                                                                for (int i = 0; i < edit.getNameList().size(); i++) {
                                                                    JSONObject userJson = new JSONObject();
                                                                    userJson.put("nickname", edit.getNameList().get(i).getUser_name());
                                                                    userJson.put("userId", edit.getNameList().get(i).getUser_id());
                                                                    jsonArray.put(userJson);
                                                                }
                                                                for (int i = 0; i < stringList.size(); i++) {
                                                                    JSONObject voteJson = new JSONObject();
                                                                    voteJson.put("name", stringList.get(i));
                                                                    jsonArrayVote.put(voteJson);
                                                                }
                                                                jsonObject.put("contentVoteJson", jsonArrayVote.toString());
                                                                jsonObject.put("remindJson", jsonArray.toString());
                                                                jsonObject.put("title", edit.getText().toString().trim());
                                                                jsonObject.put("anonymity", anonymous);
                                                                if (urlList.size() > 0) {
                                                                    if (isVideo.equals("yes")) {
                                                                        jsonObject.put("type", 1);
                                                                        jsonObject.put("videoWidth", resource.getWidth());
                                                                        jsonObject.put("videoHeight", resource.getHeight());
                                                                        jsonObject.put("videoDuration", Integer.parseInt(getDuration(finalString)) / 1000);
                                                                    } else {
                                                                        jsonObject.put("type", 2);
                                                                    }
                                                                } else {
                                                                    jsonObject.put("type", 3);
                                                                }
                                                                jsonObject.put("urls", finalString);
                                                                jsonObject.put("address", addressPoi + "|" + address);
                                                                jsonObject.put("categoriesId", tagAdapter.getItem(index).getId());
                                                                jsonObject.put("longitude", lot);
                                                                jsonObject.put("latitude", lat);
                                                                jsonObject.put("adCode", adCode);
                                                                jsonObject.put("province", province);
                                                                jsonObject.put("city", city);
                                                                jsonObject.put("district", district);
                                                                jsonObject.put("street", street);
                                                                jsonObject.put("shootTime", shootTime);
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }

                                                            Logger.e(jsonObject.toString());
                                                            finalOkGo.requestHead(RequestType.POSTJSONHEADNOCACHE, Url.PUBLISH, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                                                @Override
                                                                public void onSuccess(SendCodeBean sendCodeBean) {
                                                                    dismissDialog();
                                                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                                        btn_progress.setState(DownloadProgressButton.STATE_NORMAL);
                                                                        publishTv.setText("");
                                                                        completeImg.setVisibility(View.VISIBLE);
                                                                        handler.removeCallbacks(runnable);
                                                                        new Handler().postDelayed(new Runnable() {
                                                                            @Override
                                                                            public void run() {
                                                                                isPublish = true;
                                                                                publish.setEnabled(true);
                                                                                Bundle bundle = new Bundle();
                                                                                bundle.putString("flag", "publish");
                                                                                startFinishActivity(TransparentActivity.class, bundle);
                                                                            }
                                                                        }, 1000);
                                                                    } else {
                                                                        isPublish = true;
                                                                        showImageToas(sendCodeBean.getMsg());
                                                                        publish.setEnabled(true);
                                                                        btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                                                                        publishTv.setText("重试");
                                                                        handler.removeCallbacks(runnable);
                                                                    }
                                                                }

                                                                @Override
                                                                public void onError(Response<String> response) {
                                                                    super.onError(response);
                                                                    dismissDialog();
                                                                    isPublish = true;
                                                                    publish.setEnabled(true);
                                                                    btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                                                                    publishTv.setText("重试");
                                                                    handler.removeCallbacks(runnable);
                                                                }
                                                            });
                                                        }

                                                    });

                                        } else {
                                            JSONObject jsonObject = new JSONObject();
                                            JSONArray jsonArray = new JSONArray();
                                            JSONArray jsonArrayVote = new JSONArray();
                                            try {
                                                for (int i = 0; i < edit.getNameList().size(); i++) {
                                                    JSONObject userJson = new JSONObject();
                                                    userJson.put("nickname", edit.getNameList().get(i).getUser_name());
                                                    userJson.put("userId", edit.getNameList().get(i).getUser_id());
                                                    jsonArray.put(userJson);
                                                }
                                                for (int i = 0; i < stringList.size(); i++) {
                                                    JSONObject voteJson = new JSONObject();
                                                    voteJson.put("name", stringList.get(i));
                                                    jsonArrayVote.put(voteJson);
                                                }
                                                jsonObject.put("contentVoteJson", jsonArrayVote.toString());
                                                jsonObject.put("remindJson", jsonArray.toString());
                                                jsonObject.put("title", edit.getText().toString().trim());
                                                jsonObject.put("anonymity", anonymous);
                                                if (urlList.size() > 0) {
                                                    if (isVideo.equals("yes")) {
                                                        jsonObject.put("type", 1);
                                                    } else {
                                                        jsonObject.put("type", 2);
                                                    }
                                                } else {
                                                    jsonObject.put("type", 3);
                                                }
                                                jsonObject.put("urls", string);
                                                jsonObject.put("address", addressPoi + "|" + address);
                                                jsonObject.put("categoriesId", tagAdapter.getItem(index).getId());
                                                jsonObject.put("longitude", lot);
                                                jsonObject.put("latitude", lat);
                                                jsonObject.put("adCode", adCode);
                                                jsonObject.put("province", province);
                                                jsonObject.put("city", city);
                                                jsonObject.put("district", district);
                                                jsonObject.put("street", street);
                                                jsonObject.put("shootTime", shootTime);
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }

                                            Logger.e(jsonObject.toString());
                                            finalOkGo.requestHead(RequestType.POSTJSONHEADNOCACHE, Url.PUBLISH, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                                @Override
                                                public void onSuccess(SendCodeBean sendCodeBean) {
                                                    dismissDialog();
                                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                        btn_progress.setState(DownloadProgressButton.STATE_NORMAL);
                                                        publishTv.setText("");
                                                        completeImg.setVisibility(View.VISIBLE);
                                                        handler.removeCallbacks(runnable);
                                                        new Handler().postDelayed(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                isPublish = true;
                                                                publish.setEnabled(true);
                                                                Bundle bundle = new Bundle();
                                                                bundle.putString("flag", "publish");
                                                                startFinishActivity(TransparentActivity.class, bundle);
                                                            }
                                                        }, 1000);
                                                    } else {
                                                        isPublish = true;
                                                        showImageToas(sendCodeBean.getMsg());
                                                        publish.setEnabled(true);
                                                        btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                                                        publishTv.setText("重试");
                                                        handler.removeCallbacks(runnable);
                                                    }
                                                }

                                                @Override
                                                public void onError(Response<String> response) {
                                                    super.onError(response);
                                                    dismissDialog();
                                                    isPublish = true;
                                                    publish.setEnabled(true);
                                                    btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                                                    publishTv.setText("重试");
                                                    handler.removeCallbacks(runnable);
                                                }
                                            });
                                        }
                                    }
                                }

                            } else {
                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        isPublish = true;
                                        showImageToas(info.error);
                                        publish.setEnabled(true);
                                    }
                                });

                            }
                        }
                    }, null);
                } else {
                    showImageToas(tokenBean.getMsg());
                    isPublish = true;
                    publish.setEnabled(true);
                    btn_progress.setState(DownloadProgressButton.STATE_FINISH);
                    publishTv.setText("重试");
                    handler.removeCallbacks(runnable);
                }
            }
        });
    }

    private String getDuration(String mUri) {
        android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();
        try {
            if (mUri != null) {
                HashMap<String, String> headers = null;
                if (headers == null) {
                    headers = new HashMap<String, String>();
                }
                mmr.setDataSource(mUri, headers);
            } else {
                //mmr.setDataSource(mFD, mOffset, mLength);
            }

            String duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);//时长(毫秒)
            Logger.e("duration++++" + duration);

            return duration;
        } catch (Exception ex) {
            Logger.e("MediaMetadataRetriever exception " + ex);
        } finally {
            mmr.release();
        }
        return "0";
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                if (TextUtils.isEmpty(aMapLocation.getAdCode())) {
                    LatLonPoint point = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                    RegeocodeQuery query = new RegeocodeQuery(point, 200F, GeocodeSearch.AMAP);
                    GeocodeSearch geocoderSearch = new GeocodeSearch(context);
                    geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                        @Override
                        public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                            isLocation = true;
                            address = regeocodeResult.getRegeocodeAddress().getFormatAddress();
                            addressPoi = regeocodeResult.getRegeocodeAddress().getAois().size() == 0 ? (regeocodeResult.getRegeocodeAddress().getPois().size() == 0 ? "" : regeocodeResult.getRegeocodeAddress().getPois().get(0).getTitle()) : regeocodeResult.getRegeocodeAddress().getAois().get(0).getAoiName();
                            lot = aMapLocation.getLongitude();
                            lat = aMapLocation.getLatitude();
                            adCode = regeocodeResult.getRegeocodeAddress().getAdCode();
                            province = regeocodeResult.getRegeocodeAddress().getProvince();
                            city = regeocodeResult.getRegeocodeAddress().getCity();
                            district = regeocodeResult.getRegeocodeAddress().getDistrict();
                            street = regeocodeResult.getRegeocodeAddress().getTownship();

                            citycode = regeocodeResult.getRegeocodeAddress().getCityCode();

//                            location_tv.setText(addressPoi);

                            latLng = new LatLng(lat, lot);
                            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 18, 30, 0)));

                            LocationUtil.getInstance().stopLocation();//停止定位后，本地定位服务并不会被销毁
                        }

                        @Override
                        public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                        }

                    });

                    geocoderSearch.getFromLocationAsyn(query);

                } else {
                    isLocation = true;
                    address = aMapLocation.getAddress();
                    addressPoi = aMapLocation.getAoiName().equals("") ? aMapLocation.getPoiName() : aMapLocation.getAoiName();
                    lot = aMapLocation.getLongitude();
                    lat = aMapLocation.getLatitude();
                    adCode = aMapLocation.getAdCode();
                    province = aMapLocation.getProvince();
                    city = aMapLocation.getCity();
                    district = aMapLocation.getDistrict();
                    street = aMapLocation.getStreet();

                    citycode = aMapLocation.getCityCode();

//                    location_tv.setText(addressPoi);

                    latLng = new LatLng(lat, lot);
                    aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 18, 30, 0)));

                    LocationUtil.getInstance().stopLocation();//停止定位后，本地定位服务并不会被销毁
                }

            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Logger.e("AmapError--" + "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                showImageToas("拒绝定位权限 定位失败");
            }

        }
    }
}
